package quickstart.component

import groovy.transform.CompileStatic
import javafx.event.Event
import javafx.geometry.Insets
import javafx.scene.Node
import javafx.scene.control.Button
import javafx.scene.control.TextArea
import javafx.scene.layout.GridPane
import org.jacpfx.api.annotations.Resource
import org.jacpfx.api.annotations.component.View
import org.jacpfx.api.annotations.lifecycle.PostConstruct
import org.jacpfx.api.annotations.lifecycle.PreDestroy
import org.jacpfx.api.message.Message
import org.jacpfx.rcp.component.FXComponent
import org.jacpfx.rcp.componentLayout.FXComponentLayout
import org.jacpfx.rcp.context.Context
import org.jacpfx.rcp.util.FXUtil

import java.util.logging.Logger

import static quickstart.config.BasicConfig.*

/**
 * Created by TK-chenbin on 2015/5/20.
 */
@CompileStatic
@View(id = COMPONENT_LEFT,
        name = "SimpleView",
        active = true,
        resourceBundleLocation = "bundles.languageBundle",
        initialTargetLayoutId = TARGET_CONTAINER_LEFT)
class ComponentLeft implements FXComponent {
    private Logger log = Logger.getLogger(getClass().name)

    private Node pane
    private TextArea name

    @Resource
    private Context context

    @Override
    Node handle(final Message<Event, Object> message) throws Exception {
        return null
    }

    @Override
    Node postHandle(final Node node,
                    final Message<Event, Object> message) throws Exception {
        if (!message.messageBodyEquals(FXUtil.MessageUtil.INIT)) {
            name.text = message.getTypedMessageBody(String)
        }
        return this.pane
    }

    @PostConstruct
    void onPostConstructComponent(final FXComponentLayout layout,
                                  final ResourceBundle resourceBundle) {
        this.pane = createUI()
        log.info("run on start of ComponentLeft")
    }

    @PreDestroy
    void onPreDestroyComponent(final FXComponentLayout layout) {
        log.info("run on tear down of ComponentLeft")
    }

    private Node createUI() {
        final def main = new GridPane()
        main.padding = new Insets(0, 20, 10, 20)

        name = new TextArea()
        def sayHelloBtn = new Button("hello")
        sayHelloBtn.onAction = { event -> sayHello() }

        main.children.addAll(name, sayHelloBtn)
        return main
    }

    private void sayHello() {
        context.send(COMPONENT_RIGHT, "hello")
    }
}
